package com.yuexiang.melodyhub.authserver.handler;

import com.yuexiang.melodyhub.authserver.dto.OAuthLogin.param.OAuthLoginParam;
import com.yuexiang.melodyhub.authserver.feign.UserFeignService;
import com.yuexiang.melodyhub.authserver.handler.context.LoginContext;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizCodeConstant;
import com.yuexiang.melodyhub.common.dto.user.UserFindWithRolesByUsername.param.UserFindWithRolesByUsernameParam;
import com.yuexiang.melodyhub.common.dto.user.UserFindWithRolesByUsername.response.UserFindWithRolesByUsernameResponse;
import com.yuexiang.melodyhub.common.exception.RequestArgumentException;
import com.yuexiang.melodyhub.common.exception.gateway.UnavailableServiceException;
import com.yuexiang.melodyhub.common.handler.AbstractValidationHandler;
import com.yuexiang.melodyhub.common.result.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserLookupHandler extends AbstractValidationHandler<LoginContext> {
    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void handler(LoginContext content) {
        OAuthLoginParam param = content.getOAuthLoginParam();
        ResultData<UserFindWithRolesByUsernameResponse> userFindResponse;
        try {
            userFindResponse = userFeignService.findWithRolesByUsername(new UserFindWithRolesByUsernameParam(param.getUsername(), param.getPassword()));
        } catch (Exception e) {
            throw new UnavailableServiceException();
        }
        if (userFindResponse.getData() == null)
            throw new RequestArgumentException(BizCodeConstant.Msg.U_OR_P_IS_ERROR);
        content.setUserFindResponse(userFindResponse.getData());
        handlerNext(content);
    }
}
